import { Component, OnInit } from '@angular/core';
import { DatePipe } from '@angular/common';
import { NzMessageService } from 'ng-zorro-antd/message';
import { Router, ActivatedRoute, NavigationExtras} from '@angular/router';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { defalutImg } from '../comm';
import { CommonService } from '../../../services-common/common.service';
import { PermissionService } from '../../../service/permission.service';
import { GameManageService } from './game-manage.service';
import { divideAppStatusArrs } from '../status.pipe';
import { PromotionShareService } from '../promotion-share.service';

@Component({
  selector: 'app-game-manage',
  templateUrl: './game-manage.component.html',
  styleUrls: ['./game-manage.component.scss'],
  providers: [DatePipe]
})
export class GameManageComponent implements OnInit {

  defalutImg: string = defalutImg;
  searchOptions: Array<any> = [
    {
      type: 2,
      labelText: '审核状态',
      valueKey: 'auditStatus',
      value: [],
      multiple: true,
      notTostr: false,
      selectBindKey: { key: 'value', label: 'label' },
      selectOptions: [...divideAppStatusArrs]
    },
    {
      type: 2,
      labelText: '是否启用',
      valueKey: 'state',
      value: [],
      multiple: false,
      notTostr: false,
      selectBindKey: { key: 'value', label: 'label' },
      selectOptions: [
        {value: 0, label: '启用'},
        {value: 1, label: '禁用'}
      ]
    },
    {
      type: 2,
      labelText: '分类',
      valueKey: 'types',
      value: [],
      multiple: true,
      notTostr: false,
      selectBindKey: { key: 'id', label: 'name' },
      selectOptions: []
    },
    {
      type: 2,
      labelText: '新游推荐',
      valueKey: 'isRecommend',
      value: [],
      multiple: false,
      notTostr: false,
      selectBindKey: { key: 'value', label: 'label' },
      selectOptions: [
        {value: 0, label: '是'},
        {value: 1, label: '否'}
      ]
    }
  ];
  searchParams: any = {};
  
  // table
  tableForms: any = {
    tableLoading: false,
    page: 1,
    pageSize: 20,
    total: 0,
    pages: 0
  };
  // 表格data
  tableData: any = [];

  // 审核状态Options
  examineStatusOptions: any[] = [...divideAppStatusArrs];
  // 分类Options
  classifyOptions: any[] = [];

  /**
   * 审核 Modal
   * ----------------------------------------------------------------
   */
  isExamineVisible = false;
  examineItem: any = {};
  auditOpinion: string = '';

  constructor(
    private fb: FormBuilder,
    private datePipe: DatePipe,
    private message: NzMessageService,
    private router: Router,
    private commonService: CommonService,
    public permission: PermissionService,
    private service: GameManageService,
    private promotionShareService: PromotionShareService
  ) { }

  ngOnInit(): void {
    this.loadClassifyOptionsData();
    this.loadTable();
  }

  setSearchOption(array: Array<any>, val: string) {
    let temIndex = this.searchOptions.findIndex((item: any) => item.valueKey === val);
    this.searchOptions[temIndex].selectOptions = array || [];
  }
  
  // 查询分类Options
  async loadClassifyOptionsData() {
    let params = {
      page: 1,
      pageSize: 1000
    }
    const {code, data, message}: any = await this.promotionShareService.getGameTypeList(params);

    if (code === 0) {
      this.classifyOptions = data || [];
      this.setSearchOption(data, 'types');
    }
  }

  // loadData
  async loadTable() {
    try {
      let params = {
        ...this.searchParams,
        page: this.tableForms.page,
        pageSize: this.tableForms.pageSize
      }

      this.tableForms.tableLoading = true;
      const res: any = await this.service.gameTableData(params);
      this.tableForms.tableLoading = false;

      if (res.code == 0) {
        this.tableData = res.data.records || [];
        this.tableForms.total = res.data.total || 0;
        this.tableForms.pages = res.data.pages || 0;
      }
    } catch (error) {
      this.tableForms.tableLoading = false;

      this.tableData = [];
      this.tableForms.total = 0;
      this.tableForms.pages = 0;
    }
  }

  // 查询 | 重置
  queryResetData(params: any) {
    this.searchParams = params;
    this.tableForms.page = 1;
    this.loadTable();
  }

  // 确认删除
  async deleteConfirm(id: any) {
    let params = {
      id: id,
      state: 2 // 状态 0 启用 1禁用 2删除
    }

    try {
      const res: any = await this.service.updateGameInfo(params);
      if (res.code == 0) {
        this.message.success('删除成功');

        this.loadTable();
      } else {
        this.message.error(res.message || '删除失败');
      }
    } catch (error: any) {
      this.message.error(error || '删除失败');
    }
  }

  // 启用 || 禁用
  async onOffItem(item: any) {
    try {
      let params = {
        id: item.id,
        state: item.state == 0 ? '1' : '0'
      }
      const res: any = await this.service.updateGameInfo(params);
      if (res.code == 0) {
        this.message.success((item.state == 0 ? '禁用' : '启用') + '成功');
        this.loadTable();
      } else {
        this.message.error((item.state == 0 ? '禁用' : '启用') + '失败');
      }
    } catch (error) {
      this.message.error((item.state == 0 ? '禁用' : '启用') + '失败');
    }
  }

  // 上下移
  async sortTable(num: number, id: any) {
    try {
      const res: any = await this.service.moveTableItem({ id: id, type: num });
      if (res.code == 0) {
        this.message.success('操作成功');
        this.loadTable();
      } else {
        this.message.error(res.message || '操作失败');
      }
    } catch (error: any) {
      this.message.error(error || '操作失败');
    }
  }

  /**
   * ----------------------------------------------------------------
   * 审核
   * ----------------------------------------------------------------
   */
  showExamineModal(item: any) {
    this.examineItem = item;
    this.auditOpinion = '';
    this.isExamineVisible = true;
  }

  async subExamine(type: number) {
    if (type === 3 && this.commonService.isEmpty(this.auditOpinion)) {
      this.message.warning('请输入审核意见');
      return
    }

    let params = {
      id: this.examineItem.id,
      auditStatus: type,
      auditNote: this.auditOpinion
    }
    const res: any = await this.promotionShareService.auditAppItemData(params);

    if (res.code === 0) {
      this.isExamineVisible = false;
      this.message.success('操作成功');
      this.loadTable();
    } else {
      this.message.error(res.message);
    }
  }

  // disabled move
  disabledMoveBtn(index?: number): boolean {
    if (this.tableForms.page == this.tableForms.pages && index == this.tableData.length - 1) {
      return true
    } else {
      return false
    }
  }

  // 当前页码改变时的回调函数
  onPageIndexChange(index: number) {
    this.tableForms.page = index;
    this.loadTable()
  }
  // 页数改变时回调
  onPageSizeChange(sizeNum: number) {
    this.tableForms.page = 1;
    this.tableForms.pageSize = sizeNum;

    this.loadTable()
  }
}